import {StargateClient} from "@cosmjs/stargate";

const pkg_proto_signing = require("@cosmjs/proto-signing");

const { MsgDepositForBurnWithCaller,MsgDepositForBurn } = require("../generated/circle/cctp/v1/tx")
const { sha256 } =require("@cosmjs/crypto");
const { toHex } =require("@cosmjs/encoding");

const config = require('../config');

const height = 4218744
const txHash = "145D85359293F659DFC8341FE839B8B818EBD55F1780E976BED416F78F5473F6";
const pkg_bank_tx = require("cosmjs-types/cosmos/bank/v1beta1/tx.js");
const MsgSendUrl = '/cosmos.bank.v1beta1.MsgSend';
const MsgDepositForBurnUrl = '/circle.cctp.v1.MsgDepositForBurn';
const Web3 = require('web3');
const web3 = new Web3();
const attestationApi = config.attestationApi.url;
const main = async ()=> {

    const rpc = config.noble.url;

    const client = await StargateClient.connect(rpc)

    let block = await client.getBlock(height);

    for(let txIdx = 0; txIdx < block.txs.length; ++txIdx){

        const transactionId = toHex(sha256(block.txs[txIdx])).toUpperCase();

        console.log(txIdx , ' -- transactionId: ', transactionId);

        let tx = await client.getTx(transactionId);

        //console.log('tx: ', tx)
        let events = tx.events;
        let message;
        for(let event of events) {
            if(event.type === "circle.cctp.v1.MessageSent"){
                message = event.attributes;
                break;
            }
        }
        let m1 = message[0].value;
        //console.log('m1: ',m1);

        let tempMessage = m1.substr(1,m1.length-2);
        //console.log("tempMessage: ", tempMessage)
        var destation = Buffer.from(tempMessage, 'base64').toString('hex');
        console.log('destation: ', destation);

        let buf= Buffer.from(destation, 'hex');

        const messageHash = web3.utils.keccak256(buf);
        console.log('messageHash: ', messageHash);
        const circleUrl = attestationApi + messageHash;
        console.log('circleUrl:', circleUrl)




      let decodedTx = pkg_proto_signing.decodeTxRaw(block.txs[txIdx]);
      console.log('decodedTx: ', decodedTx);

      for(let msgIdx = 0; msgIdx < decodedTx.body.messages.length; ++msgIdx) {
          //console.log("message: ", decodedTx.body.messages[msgIdx]);
          if(decodedTx.body.messages[msgIdx].typeUrl === MsgSendUrl) {
              let msgSend = pkg_bank_tx.MsgSend.decode(decodedTx.body.messages[msgIdx].value);
              console.log("msgSend: ", msgSend);
          }else if (decodedTx.body.messages[msgIdx].typeUrl === MsgDepositForBurnUrl){
              let msg = MsgDepositForBurn.decode(decodedTx.body.messages[msgIdx].value)
              console.log('msg: ', msg);

          }
        }


    }

}

main();